package com.qn.visitor.analyze.ipaddressr.strategy;

import com.qn.visitor.model.UserVisitorRequest;
import com.qn.visitor.model.bo.analyze.IpAddressModel;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.regex.Pattern;
/**
 * qingniu-cloud user source analysis
 *
 * @Author: TXG
 * @Date: 2024/6/11
 * @Version V0.0.2
 */
@Component
public class Ip2regionAnalyze implements IpAddressrStrategy {
    private static final Pattern SPLIT_PATTERN = Pattern.compile("\\|");
    @Autowired
    Searcher searcher;
    @Override
    public IpAddressModel analyze(UserVisitorRequest ubrBo) throws Exception {
        IpAddressModel idm = new IpAddressModel();
        idm.setIp(ubrBo.getClientIp());
        if (searcher == null) {
            return idm;
        }
        String region = searcher.search(ubrBo.getClientIp());
        if (region == null) {
            return idm;
        }
        String[] splitInfos = SPLIT_PATTERN.split(region);
        // 补齐5位
        if (splitInfos.length < 5) {
            splitInfos = Arrays.copyOf(splitInfos, 5);
        }
        //国家|区域|省份|城市|ISP
        idm.setCountry(filterZero(splitInfos[0]));
        idm.setRegion(filterZero(splitInfos[1]));
        if (idm.getRegion() == null) {
            idm.setRegion(filterZero(splitInfos[2]));
        }
        idm.setCity(filterZero(splitInfos[3]));
        idm.setConnectionOrg(filterZero(splitInfos[4]));
        return idm;
    }

    private String filterZero(String info) {
        // null 或 0 返回 null
        if (info == null || BigDecimal.ZERO.toString().equals(info)) {
            return null;
        }
        return info;
    }
}